package com.chem.lems.controller;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.ExcelWriter;
import com.alibaba.excel.write.builder.ExcelWriterBuilder;
import com.alibaba.excel.write.builder.ExcelWriterSheetBuilder;
import com.alibaba.excel.write.metadata.WriteSheet;
import com.alibaba.fastjson.JSON;
import com.chem.lems.entity.Equipment;
import com.chem.lems.entity.Record;
import com.chem.lems.entity.User;
import com.chem.lems.handler.CustomCellWriteHandler;
import com.chem.lems.repository.EquipmentRepository;
import com.chem.lems.repository.RecordRepository;
import com.chem.lems.repository.UserRepository;
import com.chem.lems.serves.ExcelServices;
import com.chem.lems.vo.MenusVO;
import com.chem.lems.vo.UserExportVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Slf4j
@RestController
@RequestMapping("/excel")
public class ExcelController {
    @Autowired
    private UserRepository userRepository;
    @Autowired
    private EquipmentRepository equipmentRepository;
    @Autowired
    private RecordRepository recordRepository;

    private final String ENCODING = "UTF-8";
    private final String FILETYPE = ".xlsx";
    private final String USERFILENAME = "用户详细报表";
    private final String EQUIPFILENAME = "设备详细报表";
    private final String RECORDFILENAME = "设备借取详细报表";
    private final String TIPS = "暂无关联的设备";


    @GetMapping("user")
    public void getUserExcel(HttpServletResponse response) throws IOException {
        try {
            // Http 返回信息
            response.setContentType("application/Vnd.ms-excel");
            response.setCharacterEncoding(ENCODING);
            String fileName = URLEncoder.encode(USERFILENAME, ENCODING);
            response.setHeader("Content-Disposition", "attachment; filename*=" + ENCODING + "''" + fileName + FILETYPE);
            ServletOutputStream outputStream = response.getOutputStream();
            // 创建Excel文件
            ExcelWriter excelWriter = EasyExcel.write(outputStream).build();
            // 存放用户所关联的设备
            Map<String, List<Equipment>> equipMap = new HashMap<>();
            // 写入第一个工作表 总用户信息
            WriteSheet userSheet = EasyExcel.writerSheet(0, "全部用户信息").head(UserExportVO.class).registerWriteHandler(new CustomCellWriteHandler()).build();
            // 查询全部用户，若数据过大 可分页
            List<User> userList = userRepository.findAll();
            // 写入Excel的实体对象列表
            List<UserExportVO> exportVOS = new ArrayList<>();
            if (null != userList && !userList.isEmpty()) {
                for (User user : userList) {
                    UserExportVO exportVO = new UserExportVO(
                            user.getUserId(),
                            user.getUsername(),
                            user.getNikeName(),
                            user.getSex(),
                            user.getRoles().get(0).getRoleDesc(),
                            user.getMobile(),
                            user.getEmail(),
                            user.getCreateTime(),
                            user.getLoginTime(), TIPS);
                    if (null != user.getEquipments() && !user.getEquipments().isEmpty()) {
//                        exportVO.setEquipment(YES_TIPS_FRONT+user.getUsername()+user.getNikeName()+YES_TIPS_AFTER);
                        exportVO.setEquipment(user.getUsername()+user.getNikeName());
                        // 如果有关联设备，则会新建一个工作表 ，暂时将新工作表的数据存放的Map中
                        equipMap.put(user.getUsername()+user.getNikeName(), user.getEquipments());
                    }
                    exportVOS.add(exportVO);
                }
            }
            excelWriter.write(exportVOS, userSheet);
            //如果Map有数据，循环写入新的工作表
            if (!equipMap.isEmpty()) {
                // Sheet的索引
                int index = 1;
                for (Map.Entry<String, List<Equipment>> entry : equipMap.entrySet()) {
                    WriteSheet newSheet = EasyExcel.writerSheet(index, entry.getKey()).head(Equipment.class).build();
                    excelWriter.write(entry.getValue(), newSheet);
                    index++;
                }
            }
            excelWriter.finish();
        } catch (Exception e) {
            // 重置response
            response.reset();
            response.setContentType("application/json");
            response.setCharacterEncoding(ENCODING);
            Map<String, String> map = new HashMap<String, String>();
            map.put("status", "failure");
            map.put("message", "下载文件失败" + e.getMessage());
            response.getWriter().println(JSON.toJSONString(map));
        }
    }

    @GetMapping("equip")
    public void getEquipExcel(HttpServletResponse response) throws IOException {
        try {

            response.setContentType("application/Vnd.ms-excel");
            response.setCharacterEncoding(ENCODING);
            String fileName = URLEncoder.encode(EQUIPFILENAME, ENCODING);
            response.setHeader("Content-Disposition", "attachment; filename*=" + ENCODING + "''" + fileName + FILETYPE);
            ServletOutputStream outputStream = response.getOutputStream();
            ExcelWriterBuilder writerBuilder = EasyExcel.write(outputStream, Equipment.class);
            ExcelWriterSheetBuilder sheet = writerBuilder.sheet();
            List<Equipment> equipmentList = equipmentRepository.findAll();
            sheet.doWrite(equipmentList);
        } catch (Exception e) {
            // 重置response
            response.reset();
            response.setContentType("application/json");
            response.setCharacterEncoding(ENCODING);
            Map<String, String> map = new HashMap<String, String>();
            map.put("status", "failure");
            map.put("message", "下载文件失败" + e.getMessage());
            response.getWriter().println(JSON.toJSONString(map));
        }
    }

    @GetMapping("record")
    public void getRecordExcel(HttpServletResponse response) throws IOException {
        try {
            response.setContentType("application/Vnd.ms-excel");
            response.setCharacterEncoding(ENCODING);
            String fileName = URLEncoder.encode(RECORDFILENAME, ENCODING);
            response.setHeader("Content-Disposition", "attachment; filename*=" + ENCODING + "''" + fileName + FILETYPE);
            ServletOutputStream outputStream = response.getOutputStream();
            ExcelWriterBuilder writerBuilder = EasyExcel.write(outputStream, Record.class);
            ExcelWriterSheetBuilder sheet = writerBuilder.sheet();
            List<Record> equipmentList = recordRepository.findAll();
            sheet.doWrite(equipmentList);
        } catch (Exception e) {
            // 重置response
            response.reset();
            response.setContentType("application/json");
            response.setCharacterEncoding(ENCODING);
            Map<String, String> map = new HashMap<String, String>();
            map.put("status", "failure");
            map.put("message", "下载文件失败" + e.getMessage());
            response.getWriter().println(JSON.toJSONString(map));
        }
    }
}
